package com.mazegame.frontend;

import com.mazegame.backend.StorySceneManager;
import com.mazegame.backend.TextAnimation;
import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.media.AudioClip;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javax.swing.*;
import java.awt.*;
import java.net.URI;
import java.net.URISyntaxException;

public class ThirdStoryPanel extends JPanel implements GamePanel {
    private CardLayout cardLayout;
    private JPanel cardPanel;
    private JLayeredPane layeredPane;
    private static final int WIDTH = 1500;
    private static final int HEIGHT = 900;
    private JFXPanel jfxPanel;
    private static StorySceneManager sceneManager;// 故事场景管理器
    int userId;// 获取当前登录的用户名和ID
    int targetChapter = 3;// 当前章节
    private static AudioClip typingSound; // 音效对象
    
    static double volume = 0.5;

    //第一个场景要用到的
    private TextAnimation animation1;
    private Text text1;
    private static final String CONTENT1 = "\u3000\u3000带着疑惑你继续往前走，周围的环境不断变化着，看来是星辰轨道又移动了。走了许久，你终于看到前面有光亮，你加快步伐想要知道里面是什么。进入光亮以后，眼前闪耀着一个巨大的眼睛形状的石头，看来这就是天枢之眼了。你想要向前触碰到天枢之眼，突然眼前又是一阵光亮，出现了一个星辰迷宫，看来通过这个迷宫就知道到所有的秘密了。";
    private boolean isFirstClick1 = true;// 标记是否是第一次点击

    // 第二个场景要用到的
    private static TextAnimation animation2;
    private static Text text2;
    private static final String CONTENT2 = "\u3000\u3000通过迷宫以后，你通过阅读最后一块历史正文，知道了千年前这个城市到底发生了什么...";
    private boolean isFirstClick2 = true;


    // 第三个场景要用到的
    private TextAnimation animation3;
    private Text text3;
    private static final String CONTENT3 = "\u3000\u3000[ 星元前1015年，阿勒努斯城像一颗镶嵌在山谷中的蓝宝石，子民们踩着月光编织星图，穹顶神庙的鎏金穹顶总与北斗第七星同辉。那时的夜晚，孩童会趴在父母的膝头，听他们讲述如何用星辰之力灌溉麦田，让每粒麦穗都裹着星光。城里的石墙上刻满星轨，最年长的祭司说，这些轨迹是天地写给人间的信。\n" +
            "\u3000\u3000变故始于一群穿着黑袍的外来人。他们自称来自远方的国度，却总在深夜窥探神庙的星盘。不久后，流言像毒藤般蔓延 —— 有人说星辰之力能让人长生，有人说掌握它就能号令风雨。起初只是邻里间的窃窃私语，后来演变成街头的争吵。\n"  +
            "\u3000\u3000外来人在酒馆里煽风点火，将治理者的仁慈曲解为懦弱，把占星师的谨慎污蔑为独占秘密。当远方的领主们带着铁骑踏碎城门时，阿勒努斯已不再是那座能听见星辰私语的城，变成了争夺的竞技场，城市的土地被鲜血染红，昔日用来观测星象的青铜仪器，成了入侵者争夺的宝物。\n" +
            "\u3000\u3000治理者站在神庙之中，看着子民们蜷缩在断壁后瑟瑟发抖，北斗星的光芒在硝烟中黯淡如烛。他摘下胸前传承百年的星钥，将其嵌入神庙中央的圆盘。刹那间，万千星辉从地底涌出，在天空织成旋转的星门。“我们去寻找另一片星空。” 他的声音穿透混乱，子民们手挽手走进光里。\n" +
            "\u3000\u3000城郭在星力爆发中崩塌，只在神庙中那块眼睛形状的巨石——“天枢之眼”，瞳孔里流转着永不熄灭的微光。那些没来得及逃离的入侵者，被残留的星力扭曲了身形，成了畸形的怪物，永远徘徊在废墟周围，想要靠近“天枢之眼” 但又惧怕周围残留的星辰之力。]";
    private boolean isFirstClick3 = true;

    // 第四个场景要用到的
    private TextAnimation animation4;
    private Text text4;
    private static final String CONTENT4 = "\u3000\u3000你看到历史正文的最后写着“贪念蚀星，安宁永存”，原来传说中的天枢之眼不过是一个城市被毁灭后想要给后世留下的警示，欲望如暗潮，裹挟贪婪的漩涡吞噬理智的星光。唯有斩断对虚幻的执念，抛却无止境的索取，方能拂去心尘，让安宁常驻心间，才能长久的留存。 \n" +
            "\u3000\u3000你又陷入深深的沉思，突然神庙开始剧烈晃动，看样子是快要坍塌了，你原路返回，在神庙彻底坍塌之前跑了出来，而那个一千年前曾经向星辰一般璀璨的城市彻底消失在了这个世界......";
    private boolean isFirstClick4 = true;



    public ThirdStoryPanel(CardLayout cardLayout, JPanel cardPanel) {
        this.cardLayout = cardLayout;
        this.cardPanel = cardPanel;
        initializeUI();
    }

    private void initializeUI() {
        // 使用 JLayeredPane 管理不同层级的组件
        layeredPane = new JLayeredPane();
        setLayout(new BorderLayout());
        add(layeredPane, BorderLayout.CENTER);
        // 创建 JavaFX 内容面板
        jfxPanel = new JFXPanel();
        jfxPanel.setOpaque(false);
        jfxPanel.setBounds(0, 0, WIDTH, HEIGHT);
        layeredPane.add(jfxPanel, JLayeredPane.MODAL_LAYER);
        Platform.runLater(() -> {
            // 创建场景管理器
            sceneManager = new StorySceneManager();
            // 创建主容器
            BorderPane root = createContentPane();
            root.setStyle("-fx-background-color: rgba(0, 0, 0, 0);");
            // 将场景管理器的根节点添加到主容器中心
            root.setCenter(sceneManager.getRoot());
            // 创建透明场景
            Scene scene = new Scene(root, WIDTH, HEIGHT, javafx.scene.paint.Color.TRANSPARENT);
            jfxPanel.setScene(scene);
            // 初始化并显示第一个场景
            initScenes();
            sceneManager.showScene("scene0");
        });
    }

    private BorderPane createContentPane() {
        return new BorderPane();
    }

    // 初始化故事中的所有场景
    private void initScenes() {
        StackPane scene0 = createScene0();
        sceneManager.addScene("scene0", addBackground(scene0, "/img/黑色背景.png"));
        StackPane scene1 = createScene1();
        sceneManager.addScene("scene1", addBackground(scene1, "/img/眼.png"));
        StackPane scene2 = createScene2();
        sceneManager.addScene("scene2", addBackground(scene2, "/img/石头1.png"));
        StackPane scene3 = createScene3();
        sceneManager.addScene("scene3", addBackground(scene3, "/img/神庙.png"));
        StackPane scene4 = createScene4();
        sceneManager.addScene("scene4", addBackground(scene4, "/img/石柱.png"));
        StackPane scene5 = createScene5();
        sceneManager.addScene("scene5", addBackground(scene5, "/img/黑色背景.png"));
    }

    // 添加背景图的方法
    private Pane addBackground(Pane content, String imagePath) {
        ImageView background = new ImageView(new Image(getClass().getResourceAsStream(imagePath)));
        background.setFitWidth(WIDTH);
        background.setFitHeight(HEIGHT);
        StackPane stackPane = new StackPane();
        stackPane.getChildren().addAll(background, content);
        return stackPane;
    }
    private StackPane createScene0() {
        StackPane root = new StackPane();
        Text content = new Text("\u3000\u3000第三章");
        content.setWrappingWidth(900);
        content.setFont(new Font("微软雅黑", 48));
        content.setFill(Color.WHITE);
        content.setVisible(true);
        VBox textbox = new VBox(40);//每个文本间隔20
        textbox.getChildren().add(content);//把文本放进面板
        textbox.setAlignment(Pos.CENTER);//文本居中放置
        textbox.setPadding(new Insets(0));//页边距20
        textbox.setPrefSize(900, 600);
        textbox.setMaxSize(900, 600);
        javafx.scene.control.Label tip = new Label("点击任意位置继续...");
        tip.setFont(Font.font("KaiTi", FontWeight.BOLD, 32));
        tip.setTextFill(Color.WHITE);
        root.setMargin(textbox,new Insets(0,0,200, 520));
        root.setMargin(tip,new Insets(500,0,0,0));
        root.getChildren().addAll(textbox, tip);
        // 添加点击事件：点击任意位置切换到下一个场景
        root.setOnMouseClicked(event -> {
            startFirstStory1();
        });
        return root;
    }
    private StackPane createScene1() {
        // 构建文本1
        text1 = new Text("");
        text1.setWrappingWidth(860);
        text1.setFont(new javafx.scene.text.Font("微软雅黑", 32));
        text1.setFill(javafx.scene.paint.Color.BLACK);
        // 文本容器
        VBox textbox = new VBox(20);//每个文本间隔20
        textbox.getChildren().add(text1);//把文本放进面板
        textbox.setAlignment(Pos.CENTER);//文本居中放置
        textbox.setPadding(new javafx.geometry.Insets(20));//页边距20
        textbox.setPrefSize(900, 400);
        textbox.setMaxSize(900, 400);
        textbox.setStyle("-fx-background-color: rgba(255, 255, 255, 0.6);" +
                "-fx-border-radius: 40;" +
                "-fx-background-radius: 40;" +
                "-fx-effect: dropshadow(three-pass-box, rgba(0, 0, 0, 0.5), 10, 0, 0, 0);" +
                "-fx-stroke: grey;"
        );
        javafx.scene.control.Label tip = new javafx.scene.control.Label("点击任意位置继续...");
        tip.setFont(javafx.scene.text.Font.font("KaiTi", FontWeight.BOLD, 48));
        tip.setTextFill(javafx.scene.paint.Color.WHITE);
        StackPane.setMargin(textbox, new javafx.geometry.Insets(0,0 ,0,0));
        StackPane.setMargin(tip, new javafx.geometry.Insets(640,0 ,0,0));
        // 布局容器
        StackPane stackPane = new StackPane();
        stackPane.getChildren().addAll(textbox,tip);//添加到面板
        // 添加点击事件：点击任意位置切换到下一个场景
        stackPane.setOnMouseClicked(event -> {
            if (isFirstClick1) {
                stopAnimationAndSound1();
                isFirstClick1 = false;  // 更新状态为已点击一次
            } else {
                //进迷宫
                MazeGeneratePanel.isFirst = true;
                BufferPanel.isFirst = true;
                cardLayout.show(cardPanel,"MAZEGENERATEPANEL");
            }
        });
        return stackPane;
    }
    private StackPane createScene2() {
        // 构建文本1
        text2 = new Text("");
        text2.setWrappingWidth(760);
        text2.setFont(new javafx.scene.text.Font("微软雅黑", 32));
        text2.setFill(javafx.scene.paint.Color.BLACK);
        // 文本容器
        VBox textbox = new VBox(20);//每个文本间隔20
        textbox.getChildren().addAll(text2);//把文本放进面板
        textbox.setAlignment(Pos.CENTER);//文本居中放置
        textbox.setPadding(new javafx.geometry.Insets(20));//页边距20
        textbox.setPrefSize(800, 200);
        textbox.setMaxSize(800, 200);
        textbox.setStyle("-fx-background-color: rgba(255, 255, 255, 0.6);" +
                "-fx-border-radius: 40;" +
                "-fx-background-radius: 40;" +
                "-fx-effect: dropshadow(three-pass-box, rgba(0, 0, 0, 0.5), 10, 0, 0, 0);" +
                "-fx-stroke: grey;"
        );
        javafx.scene.control.Label tip = new javafx.scene.control.Label("点击任意位置继续...");
        tip.setFont(javafx.scene.text.Font.font("KaiTi", FontWeight.BOLD, 48));
        tip.setTextFill(javafx.scene.paint.Color.WHITE);
        StackPane.setMargin(textbox, new javafx.geometry.Insets(0,0 ,0,0));
        StackPane.setMargin(tip, new javafx.geometry.Insets(640,0 ,0,0));
        // 布局容器
        StackPane stackPane = new StackPane();
        stackPane.getChildren().addAll(textbox,tip);//添加到面板
        // 添加点击事件：点击任意位置切换到下一个场景
        stackPane.setOnMouseClicked(event -> {
            if (isFirstClick2) {
                stopAnimationAndSound2();
                isFirstClick2 = false;  // 更新状态为已点击一次
            } else {
                // 第二次点击：跳转到下一个场景
                startFirstStory3();
                //进迷宫
            }
        });
        return stackPane;
    }
    private StackPane createScene3() {
        // 构建文本1
        text3 = new Text("");
        text3.setWrappingWidth(1260);
        text3.setFont(new javafx.scene.text.Font("微软雅黑", 28));
        text3.setFill(javafx.scene.paint.Color.BLACK);
        // 文本容器
        VBox textbox = new VBox(20);//每个文本间隔20
        textbox.getChildren().addAll(text3);//把文本放进面板
        textbox.setAlignment(Pos.CENTER);//文本居中放置
        textbox.setPadding(new javafx.geometry.Insets(20));//页边距20
        textbox.setPrefSize(1300, 640);
        textbox.setMaxSize(1200, 640);
        textbox.setStyle("-fx-background-color: rgba(255, 255, 255, 0.6);" +
                "-fx-border-radius: 40;" +
                "-fx-background-radius: 40;" +
                "-fx-effect: dropshadow(three-pass-box, rgba(0, 0, 0, 0.5), 10, 0, 0, 0);" +
                "-fx-stroke: grey;"
        );
        javafx.scene.control.Label tip = new javafx.scene.control.Label("点击任意位置继续...");
        tip.setFont(javafx.scene.text.Font.font("KaiTi", FontWeight.BOLD, 48));
        tip.setTextFill(javafx.scene.paint.Color.WHITE);

        StackPane.setMargin(textbox, new javafx.geometry.Insets(0,0 ,100,0));
        StackPane.setMargin(tip, new javafx.geometry.Insets(640,0 ,0,0));
        // 布局容器
        StackPane stackPane = new StackPane();
        stackPane.getChildren().addAll(textbox,tip);//添加到面板
        // 添加点击事件：点击任意位置切换到下一个场景
        stackPane.setOnMouseClicked(event -> {
            if (isFirstClick3) {
                stopAnimationAndSound3();
                isFirstClick3 = false;  // 更新状态为已点击一次
            } else {
                startFirstStory4();
            }
        });
        return stackPane;
    }
    private StackPane createScene4() {
        // 构建文本1
        text4 = new Text("");
        text4.setWrappingWidth(860);
        text4.setFont(new javafx.scene.text.Font("微软雅黑", 32));
        text4.setFill(javafx.scene.paint.Color.BLACK);
        // 文本容器
        VBox textbox = new VBox(20);//每个文本间隔20
        textbox.getChildren().addAll(text4);//把文本放进面板
        textbox.setAlignment(Pos.CENTER);//文本居中放置
        textbox.setPadding(new javafx.geometry.Insets(20));//页边距20
        textbox.setPrefSize(900, 500);
        textbox.setMaxSize(900, 500);
        textbox.setStyle("-fx-background-color: rgba(255, 255, 255, 0.6);" +
                "-fx-border-radius: 40;" +
                "-fx-background-radius: 40;" +
                "-fx-effect: dropshadow(three-pass-box, rgba(0, 0, 0, 0.5), 10, 0, 0, 0);" +
                "-fx-stroke: grey;"
        );
        javafx.scene.control.Label tip = new Label("点击任意位置继续...");
        tip.setFont(Font.font("KaiTi", FontWeight.BOLD, 48));
        tip.setTextFill(Color.WHITE);

        StackPane.setMargin(textbox, new javafx.geometry.Insets(0,0,0,0));
        StackPane.setMargin(tip, new Insets(640,0 ,0,0));
        // 布局容器
        StackPane stackPane = new StackPane();
        stackPane.getChildren().addAll(textbox,tip);//添加到面板
        // 添加点击事件：点击任意位置切换到下一个场景
        stackPane.setOnMouseClicked(event -> {
            if (isFirstClick4) {
                stopAnimationAndSound4();
                isFirstClick4 = false;  // 更新状态为已点击一次
            } else {
                sceneManager.showScene("scene5");
            }
        });
        return stackPane;
    }
    private StackPane createScene5() {
        StackPane root = new StackPane();
        Text content = new Text("\u3000\u3000第三章结束");
        content.setWrappingWidth(900);
        content.setFont(new Font("微软雅黑", 48));
        content.setFill(Color.WHITE);
        content.setVisible(true);
        VBox textbox = new VBox(40);//每个文本间隔20
        textbox.getChildren().add(content);//把文本放进面板
        textbox.setAlignment(Pos.CENTER);//文本居中放置
        textbox.setPadding(new Insets(0));//页边距20
        textbox.setPrefSize(900, 600);
        textbox.setMaxSize(900, 600);
        javafx.scene.control.Label tip = new Label("点击任意位置继续...");
        tip.setFont(Font.font("KaiTi", FontWeight.BOLD, 32));
        tip.setTextFill(Color.WHITE);
        root.setMargin(textbox,new Insets(0,0,200, 430));
        root.setMargin(tip,new Insets(500,0,0,0));
        root.getChildren().addAll(textbox, tip);
        root.setOnMouseClicked(event -> {
            update();
        });

        return root;
    }
    private void update() {
//        targetChapter = 3; // 解锁第三章节
//        userId = Integer.parseInt(LoginPanel.currentUserId);
//        // 保存游戏进度
//        if (UserDAO.updateChapter(userId, targetChapter)) {
//            System.out.println("游戏进度保存成功！");
//        } else {
//            System.out.println("游戏进度保存失败！");
//        }
//        ChapterPanel.update();
        // 切换回章节界面
        cardLayout.show(cardPanel, "CHAPTERPANEL");
        // 重置
        text1.setText("");
        text2.setText("");
        text3.setText("");
        text4.setText("");
        isFirstClick1 = true;
        isFirstClick2 = true;
        isFirstClick3 = true;
        isFirstClick4 = true;
        sceneManager.showScene("scene0");
    }
    public void stopAnimationAndSound1(){
        // 停止动画和音效，显示全文
        if (animation1 != null) {
            animation1.stop(); // 现在可以调用 stop
        }
        typingSound.stop();
        text1.setText(CONTENT1);
        isFirstClick1 = false;
    }
    public void stopAnimationAndSound2(){
        // 停止动画和音效，显示全文
        if (animation2 != null) {
            animation2.stop(); // 现在可以调用 stop
        }
        typingSound.stop();
        text2.setText(CONTENT2);
        isFirstClick2 = false;
    }
    public void stopAnimationAndSound3(){
        // 停止动画和音效，显示全文
        if (animation3 != null) {
            animation3.stop(); // 现在可以调用 stop
        }
        typingSound.stop();
        text3.setText(CONTENT3);
        isFirstClick3 = false;
    }
    public void stopAnimationAndSound4(){
        // 停止动画和音效，显示全文
        if (animation4 != null) {
            animation4.stop(); // 现在可以调用 stop
        }
        typingSound.stop();
        text4.setText(CONTENT4);
        isFirstClick4 = false;
    }
    public void startFirstStory1() {
        sceneManager.showScene("scene1");
        // 加载音效
        URI soundUri = null;
        try {
            soundUri = getClass().getResource("/music/打字机音效.wav").toURI();
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
        typingSound = new AudioClip(soundUri.toString());
        typingSound.setVolume(volume);//音量
        typingSound.setCycleCount(AudioClip.INDEFINITE);//无限循环播放
        // 启动文本动画
        animation1 = new TextAnimation(
                text1,
                CONTENT1,
                TextAnimation.DEFAULT_CHARACTER_DELAY,
                TextAnimation.DEFAULT_TEXT_DELAY,
                typingSound
        );
        animation1.start();
    }
    public static void startFirstStory2() {
        sceneManager.showScene("scene2");
        // 加载音效
        URI soundUri = null;
        try {
            soundUri = ThirdStoryPanel.class.getResource("/music/打字机音效.wav").toURI();
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
        typingSound = new AudioClip(soundUri.toString());
        typingSound.setVolume(volume);//音量
        typingSound.setCycleCount(AudioClip.INDEFINITE);//无限循环播放
        // 启动文本动画
        animation2 = new TextAnimation(
                text2,
                CONTENT2,
                TextAnimation.DEFAULT_CHARACTER_DELAY,
                TextAnimation.DEFAULT_TEXT_DELAY,
                typingSound
        );
        animation2.start();
    }
    public void startFirstStory3() {
        sceneManager.showScene("scene3");
        // 加载音效
        URI soundUri = null;
        try {
            soundUri = getClass().getResource("/music/打字机音效.wav").toURI();
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
        typingSound = new AudioClip(soundUri.toString());
        typingSound.setVolume(volume);//音量
        typingSound.setCycleCount(AudioClip.INDEFINITE);//无限循环播放
        // 启动第一个文本动画
        animation3 = new TextAnimation(
                text3,
                CONTENT3,
                TextAnimation.DEFAULT_CHARACTER_DELAY,
                TextAnimation.DEFAULT_TEXT_DELAY,
                typingSound
        );
        animation3.start();
    }
    public void startFirstStory4() {
        sceneManager.showScene("scene4");
        // 加载音效
        URI soundUri = null;
        try {
            soundUri = FirstStoryPanel.class.getResource("/music/打字机音效.wav").toURI();
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
        typingSound = new AudioClip(soundUri.toString());
        typingSound.setVolume(volume);//音量
        typingSound.setCycleCount(AudioClip.INDEFINITE);//无限循环播放
        // 启动本动画
        animation4 = new TextAnimation(
                text4,
                CONTENT4,
                TextAnimation.DEFAULT_CHARACTER_DELAY,
                TextAnimation.DEFAULT_TEXT_DELAY,
                typingSound
        );
        animation4.start();
    }


    @Override
    public void showPanel() {
        cardLayout.show(cardPanel, "THIRDSTORYPANEL");
    }

    @Override
    public void cleanup() {
        // 清理资源
    }


}